<?php
/**
 * Created by PhpStorm.
 * User: 悟能科技
 * Date: 2018/8/27
 * Time: 15:49
 */

namespace app\mobile\controller;


use app\common\controller\ActionLogs;
use app\common\controller\Platurl;
use app\common\model\CardGive;
use app\common\model\CardGivecardLog;
use app\common\model\CardGivePutCard;
use app\common\model\CardMember;
use app\common\model\CardUserBonus;
use app\common\model\CardUserGet;
use app\common\model\CardUserUpdate;
use app\common\model\Momerchant;
use app\common\model\WxOpen;
use app\index\controller\Wxcard;
use think\Request;
use think\Session;
use Wechat\Wxobjopen;
use Wnkj\WnCardObj;
use Wnkj\WnObj;

class Cardacitvate extends Mobilebase
{
    //激活
    public function cardfire(Request $request)
    {
//        try {
        $ActionLogs = new ActionLogs();

            $this->_init();
            $param = $request->param();
            $ActionLogs-> writelog("payos","cardacitvate","biz/cardfire","1:",$param);
            $openid = $param['openid'];
            $CardUserGet = new CardUserGet();
            $user = $CardUserGet->where(['card_id' => $param['card_id'], 'openid' => $openid])->field('code,card_id,id,fire,have,c_id,openid,mid')->find();
            if ($user['fire'] == 0) {
                $getusercode = $this->decrptusercode($param);
                $ActionLogs-> writelog("payos","cardacitvate","biz/cardfire","2:",$getusercode);
                if ($getusercode['errcode'] == 0) {
                    $getuser['activate_ticket'] = $param['activate_ticket'];
                    $userres = $this->getfireinfo($param['card_id'], $getuser);      //获取激活信息
                    $ActionLogs-> writelog("payos","cardacitvate","biz/cardfire","3:",$userres);
                    if ($userres['errcode'] == 0) {
                        $userdata = $userres['data'];
                        $userdata['activate_ticket'] = $param['activate_ticket'];
                        $CardUserGet = new CardUserGet();
                        $map['code'] = $getusercode['code'];
                        $map['card_id'] = $param['card_id'];
                        $CardUserGet->allowField(true)->save($userdata, ['id' => $user['id']]);
                        $fire = $this->usercardfire($param['card_id'], $getusercode['code'], $user['id'], $user['c_id'],$user['fire'],$user['openid']);        //激活
                        $ActionLogs-> writelog("payos","cardacitvate","biz/cardfire","6:",$fire);
                        if ($fire['errcode'] == 0) {
                            $res = $this->getuserfireinfo($param['card_id'], $getusercode['code'], $user['id']);
                       //     if ($user['mid'] == 501) {
                                if ($res['code'] == 1) {
                                    $this->redirect(url('cardget/getfirecards', ['card_id' => $user['card_id'], 'rec_id' => $res['give_rec_id']]));
                                } else {
                                    $this->redirect(url('carduser/opencard', ['card_id' => $param['card_id']]));
                                }
//                            }else{
//                                $this->redirect(url('carduser/opencard', ['card_id' => $param['card_id']]));
//                            }
                        } else {
                            echo '激活失败';        //激活
                        }

                    } else {
                        echo '激活失败';        //获取激活信息
                    }

                } else {
                    echo '激活失败';        //解密失败
                }
            } else {
                //已激活
                $this->assign('card', $param);
                return $this->fetch();
            }
//        } catch (\Exception $e) {
//            $ActionLogs = new ActionLogs();
//            $ActionLogs->writelog("payos", "mobile", "cardacitvate/" . 'cardfire', "接收推送信息:", $e->getMessage());
//            return $this->fetch('syserror');
//        }
    }

    //解码
    public function decrptusercode($param)
    {
        $options = $this->options($param['card_id']);
        $WxObj = new Wxobjopen($options);
        $map['card_id'] = $param['card_id'];
        $codedata['encrypt_code'] = $param['encrypt_code'];
        $resc = $WxObj->decryptCode($codedata);
        return $resc;
    }


    //查询激活信息
    public function getfireinfo($card_id, $data)
    {
        $options = $this->options($card_id);
        $wxObj = new Wxobjopen($options);
        $res = $wxObj->getuserActivate($data);
        $userinfo = [];
        if ($res['errcode'] == 0) {
            $userinfo['data'] = $this->fillgetinfo($res);
            $userinfo['errcode'] = 0;
        } else {
            $userinfo['errcode'] = 1;
        }
        return $userinfo;
    }

    //激活会员卡
    public function usercardfire($card_id, $code, $us_c_id, $c_id,$fire,$openid)
    {
        $ActionLogs = new ActionLogs();
        $CardUserGet = new CardUserGet();
//        $user = $CardUserGet->where(['id' => $us_c_id])->field('openid,fire')->find();
        if ($fire == 0) {
            $CardMember = new CardMember();
            $card = $CardMember->where(['card_id' => $card_id])->field('supply_bonus,bonus_rule,id,mid')->find();
            if ($card['supply_bonus'] == 1) {
                $bonus_rule = json_decode($card['bonus_rule'], true);
//                $data['init_bonus'] = $bonus_rule['init_increase_bonus']/2;
//                $data['init_bonus_record'] = '激活赠送';
            }
            $data['membership_number'] = $code;
            $data['code'] = $code;
            $data['card_id'] = $card_id;
            $options = $this->options($card_id);
            $wxObj = new Wxobjopen($options);
            $res = $wxObj->cardFire($data);
            $ActionLogs-> writelog("payos","cardacitvate","biz/cardfire","4:",$res);
            if ($res['errcode'] == 0) {
                $datass['card_id'] = $card_id;
                $datass['openid'] = $openid;
                $datass['code'] = $code;
                $datass['us_c_id'] = $us_c_id;
                $datass['c_id'] = $c_id;
                if ($card['supply_bonus'] == 1) {
                    $datass['add_bonus'] = $bonus_rule['init_increase_bonus'];
                } else {
                    $datass['add_bonus'] = 0;
                }
                $datass['con_username'] = 'FIREGIFT';
                $datass['record_bonus'] = '激活赠送';
                $datass['hx_fs'] = 25;
                $datass['type'] = 3;
                $datass['cate'] = 1;
                $datass['reason'] = 4;
                $datass['source'] = 7;
                $datass['create_time'] = time();
                $datass['mid'] = $card['mid'];
//                $CardUserUpdate = new CardUserUpdate();
//                $CardUserUpdate->allowField(true)->save($datass);
                //END
                $CardUserGet->allowField(true)->save(['fire' => 1], ['id' => $us_c_id]);
                $ActionLogs-> writelog("payos","cardacitvate","biz/cardfire","5:",$CardUserGet->getLastSql());
                //END
                $CardUserBonus = new CardUserBonus();
                $mac['card_id'] = $datass['card_id'];
                $mac['code'] = $datass['code'];
                $mac['cate'] = 5;
                $mac['action_user'] = 'FIREGIFT';
                $is_us_bonus = $CardUserBonus->where($mac)->value('id');
                if (!$is_us_bonus) {
                    $this->firebonus($datass);
                }
            }
        } else {
            $res['errcode'] = 0;
        }
        return $res;
    }

    //激活赠送积分
    private function firebonus($param){
        try{
            $data['card_id'] = $param['card_id'];
            $data['code'] = $param['code'];
            $data['num'] = $param['add_bonus'];
            $data['type'] = 1;
            $data['cate'] = 5;
            $data['pay_cate'] = 25;
            $data['source'] = 'onlines';
            $data['orderid'] = '';
            $data['remark'] = $param['record_bonus']; //备注
            $data['action_user'] = $param['con_username'];//操作人
            $data['is_write'] = 'no';
            $data['bd_cate'] = 'bonus';
            $Fztest = new WnCardObj($data);
            $Fztest->init();
        } catch (\Exception $e) {
            $res = json_encode(array('code' => '9099', 'message' => $e->getMessage()));
            $ActionLogs = new ActionLogs();
            $ActionLogs-> writelog("payos","cardacitvate","firebonus/error","e:",$res);
        }
    }

    //拉取会员信息
    public function getuserfireinfo($card_id, $code, $us_c_id)
    {
        $options = $this->options($card_id);
        $wxObj = new Wxobjopen($options);
        $data['card_id'] = $card_id;
        $data['code'] = $code;
        $res = $wxObj->userGetInfo($data);
        if ($res['errcode'] == 0) {
            $arr['nickname'] = $res['nickname'];
            $arr['sex'] = $res['sex'] == 'MALE' ? 1 : 0;
            $CardUserGet = new CardUserGet;
            $CardUserGet->save($arr, ['id' => $us_c_id]);
        }
        $datas = $CardUserGet->where(['id' => $us_c_id])->field('card_id,code,openid,outerstr,top_mid,mid')->find();
        $datas['type'] = 'firecard';
        $datas['get_code'] = $datas['code'];
        $datas['get_openid'] = $datas['openid'];
        $Wxcard = new Wxcard();
        $Wxcard->shareget($datas);  //分享奖励
        $data['openid']=$datas['openid'];
        $res = $this->getfirecard($data);
        return $res;
    }

    //激活送券
    /*
     *card_id
     *
     */
    public function getfirecard($param)
    {
        $CardGive = new CardGive();
        $CardUserGet = new CardUserGet();
        $sql['card_id'] =  $param['card_id'];
        $sql['statu'] =  ['neq',2];
        $giveinfo = $CardGive->where($sql)->find();
        //END
        $Momerchant = new Momerchant();
        $sinfo = $Momerchant->where('id', $giveinfo['top_mid'])->value('wx_open_id');
        $WxOpen = new WxOpen();
        $sappid = $WxOpen->where('id', $sinfo)->value('authorizer_appid');
        $openid = Session::get($sappid . '_openid');
        if(!$openid){
            $openid=$param['openid'];
        }
        //END
        $user = $CardUserGet->where(['card_id' => $giveinfo['card_id'], 'openid' => $openid])->field('c_id,id,fire,top_mid,mid,code,card_id,openid')->find();
        if ($user['fire'] == "1" || $user['fire'] == 1) {
            if ($giveinfo) {
                if ($giveinfo['end_time'] > time()) {
                    if ($giveinfo['card_no'] > 0) {
                        $data['card_id_list'] = $giveinfo['card_id_list'];
                        $data['give_id'] = $giveinfo['id'];
                        $CardGivePutCard = new CardGivePutCard();
                        $data['top_mid'] = $user['top_mid'];
                        $data['us_c_id'] = $user['id'];
                        $data['c_id'] = $user['c_id'];
                        $data['mid'] = $user['mid'];
                        $data['code'] = $user['code'];
                        $data['card_id'] = $user['card_id'];
                        $data['openid'] = $user['openid'];
                        $data['give_type'] = 'fire_card';
                        $data['give_id'] = $giveinfo['id'];
                        $data['create_time'] = time();
                        $CardGivePutCard->allowField(true)->save($data);
                        $data['give_rec_id'] = $CardGivePutCard->id;
                        $res = $this->get_fire_cardslog($data);
                        $resut['card'] = $res;
                        $datac['giveinfo'] = json_encode($resut, JSON_UNESCAPED_UNICODE);
                        $CardGivePutCard->allowField(true)->save($datac, ['id' => $data['give_rec_id']]);
                        //END
//                        $Platurl = new Platurl();
//                        $agent_url = $Platurl->getagenturl('card_id',$user['card_id']);
                        $resut['give_rec_id'] = $data['give_rec_id'];
                        $resut['code'] = 1;
                        $resut['card'] = '赠送成功';
                    } else {
                        $resut['code'] = 2;
                        $resut['card'] = '无券赠送1';
                    }
                } else {
                    $resut['code'] = 3;
                    $resut['card'] = '已结束';
                }
            } else {
                $resut['code'] = 4;
                $resut['card'] = '无券赠送2';
            }
        } else {
            $resut['code'] = 5;
            $resut['card'] = '未激活';
        }
        return $resut;
    }

    //开卡送券记录
    public function get_fire_cardslog($arr)
    {
        $CardGivecardLog = new CardGivecardLog();
        $zs_card_id = $arr['card_id_list'];
        if ($zs_card_id) {
            $zs_card_id = json_decode($zs_card_id,true);
            $datass['cardlist'] = $zs_card_id;
            $WnObj = new WnObj($datass);
            $arrs = $WnObj->isgetputsume_rec();
            $data = [];
            if (!empty($arrs)) {
                $CardUserGet = new CardUserGet();
                $user = $CardUserGet->where(array('openid'=>$arr['openid'],'card_id'=>$arr['card_id']))->field('id,c_id')->find();
                foreach ($arrs as $k => $v) {
                    $data[$k]['card_id'] = $arr['card_id'];
                    $data[$k]['openid'] = $arr['openid'];
                    $data[$k]['us_c_id'] = $user['id'];
                    $data[$k]['c_id'] = $user['c_id'];
                    $data[$k]['code'] = $arr['code'];
                    $data[$k]['zs_card_id'] = $v['card_id'];
                    $data[$k]['give_rec_id'] = $arr['give_rec_id'];
                    $data[$k]['mid'] = $arr['mid'];
                    $data[$k]['top_mid'] = $arr['top_mid'];
                    $data[$k]['put_sume'] = $v['zs_no'];
                    $data[$k]['put_type'] = 'fire_card';
                    $data[$k]['create_time'] = time();
                }
            }


//            $zs_cards_list = json_decode(search_cards_info($zs_card_id), true);
//            if ($zs_card_id) {
//
//                foreach ($zs_cards_list as $k => $v) {
//
//                    $data[$k]['card_id'] = $arr['card_id'];
//                    $data[$k]['openid'] = $arr['openid'];
//                    $data[$k]['code'] = $arr['code'];
//                    $data[$k]['put_type'] = 'fire_card';
//                    $data[$k]['zs_card_id'] = $v['zs_card_id'];
//                    $data[$k]['give_rec_id'] = $arr['give_rec_id'];
//                    $data[$k]['mid'] = $arr['mid'];
//                    $data[$k]['top_mid'] = $arr['top_mid'];
//                    $data[$k]['put_sume'] = $v['zs_no'];
//                    $data[$k]['time_type'] = $v['time_type'];
//                    $data[$k]['end_time'] = $v['end_timestamp'];
//                    $data[$k]['create_time'] = time();
//
//                }
//            }
//            if (isset($data)) {
                $res = $CardGivecardLog->allowField(true)->saveAll($data);
//            }
        } else {
            $res = 'no card send';
        }
        return $res;
    }


    public function fillgetinfo($info)
    {
        $param = $info['info']['common_field_list'];
        foreach ($param as $k => $v) {
            switch ($v['name']) {
                case "USER_FORM_INFO_FLAG_MOBILE":          //手机
                    $arr['phone'] = $v['value'];
                    break;
                case "USER_FORM_INFO_FLAG_LOCATION":        //地址
                    if (isset($v['value'])) {
                        $arr['address'] = $v['value'];
                    } else {
                        $arr['address'] = '';
                    }
                    break;
                case "USER_FORM_INFO_FLAG_BIRTHDAY":        //生日
                    if (isset($v['value'])) {
                        $arr['birthday'] = $v['value'];
                        $arr['feteday'] = date("m-d", strtotime($v['value']));
                    } else {
                        $arr['birthday'] = '';
                        $arr['feteday'] = '';
                    }
                    break;
                case "USER_FORM_INFO_FLAG_NAME":            //姓名
                    if (isset($v['value'])) {
                        $arr['name'] = $v['value'];
                    } else {
                        $arr['name'] = '';
                    }
                    break;
                case "USER_FORM_INFO_FLAG_IDCARD":          //身份证
                    if (isset($v['value'])) {
                        $arr['idnumber'] = $v['value'];
                    } else {
                        $arr['idnumber'] = '';
                    }
                    break;
                case "USER_FORM_INFO_FLAG_EMAIL":           //邮箱
                    if (isset($v['value'])) {
                        $arr['email'] = $v['value'];
                    } else {
                        $arr['email'] = '';
                    }
                    break;
                case "USER_FORM_INFO_FLAG_EDUCATION_BACKGRO":       //背景
                    if (isset($v['value'])) {
                        $arr['backgro'] = $v['value'];
                    } else {
                        $arr['backgro'] = '';
                    }
                    break;
                case "USER_FORM_INFO_FLAG_INDUSTRY":        //行业
                    if (isset($v['value'])) {
                        $arr['industry'] = $v['value'];
                    } else {
                        $arr['industry'] = '';
                    }
                    break;
                case "USER_FORM_INFO_FLAG_INCOME":          //收入
                    if (isset($v['value'])) {
                        $arr['income'] = $v['value'];
                    } else {
                        $arr['income'] = '';
                    }
                    break;
                case "USER_FORM_INFO_FLAG_HABIT":           //兴趣
                    if (isset($v['value'])) {
                        $arr['habit'] = $v['value'];
                    } else {
                        $arr['habit'] = '';
                    }
                    break;
            }
        }
        if (isset($info['user_info']['custom_field_list'])) {
            foreach ($info['user_info']['custom_field_list'] as $k => $v) {
                $userinfo[$v['name']] = $v['value'];
            }
            if (isset($userinfo)) {
                $arr['fireinfo'] = json_encode($userinfo, JSON_UNESCAPED_UNICODE);
                if (isset($userinfo['实体卡号'])) {
                    $arr['old_code'] = $userinfo['实体卡号'];
                }
            }
        }
//        $arr['nickname'] = $info['nickname'];
//        $arr['sex'] = $info['sex'] == 'MALE' ? 1 : 0;
        //     $arr['fire'] =1;
        $arr['fire_time'] = time();
//        $arr['fire'] = 1;
        return $arr;
    }

}